<template>
  <div>
    <home-header></home-header>

    <home-nav
        @selectedNav="selectedNav">
    </home-nav>

    <home-content
        :topList="topList"
        :hot="hot"
        :isAjax="isAjax"
        :article="article"
        @selectOrder="selectOrder"
        @ajaxNext="ajaxNext">
    </home-content>
  </div>
</template>

<script>
import HomeHeader from "@/pages/common/Header";
import HomeNav from "@/pages/common/Nav";
import HomeContent from "./components/Content";

import {category, index, topic} from "@/api/index";

export default {
  name: 'Home',
  props: {
    categoryId: Number
  },
  components: {
    HomeHeader,
    HomeNav,
    HomeContent
  },
  data () {
    return {
      topList: [], // 话题列表
      hot: [], // 本周热议
      article: {}, // 文章列表
      page: 1, // 页码
      perPage: 6, // 每页数量
      isAjax: true // 是否还有下一页
    }
  },
  methods: {
    getIndex() {
      index(this.$store.state.navCategory).then(this.getIndexSucc)
    },
    getIndexSucc(res) {
      res = res.data.data
      if (res.topic.length < this.perPage) {
        this.isAjax = false
      }
      this.topList = res.topic
      this.article = res.article
      this.hot = res.hot
    },
    initCommon () {
      category().then(this.getInitSucc);
    },
    getInitSucc (res) {
      // console.log(res.data.data)
      this.$store.state.navs = res.data.data
    },
    selectedNav(categoryId, page) {
      // 每次切换导航栏的初始化
      this.page = 1
      this.isAjax = true

      topic(categoryId, page, this.perPage, this.$store.state.indexOrder).then(this.getTopicSucc)
    },
    getTopicSucc(res) {
      res = res.data.data
      if (res.list.length < this.perPage) {
        this.isAjax = false
      }
      this.topList = res.list
    },
    ajaxNext(categoryId, order = '') {
      this.page++
      topic(categoryId, this.page, this.perPage, order).then(this.getAjaxNextSucc)
    },
    selectOrder(categoryId, order = '') {
      this.topList = [];
      this.page = 1
      this.isAjax = true
      topic(categoryId, this.page, this.perPage, order).then(this.getAjaxNextSucc)
    },
    getAjaxNextSucc(res) {
      res = res.data.data
      if (res.list.length < this.perPage) {
        this.isAjax = false
      }
      this.topList = this.topList.concat(res.list)
    }

  },
  mounted () {
    this.getIndex()
    this.initCommon()
  }
}
</script>

<style scoped>
</style>
